/*
 * RawMediaWriter.cpp
 *
 *  Created on: 2017年3月5日
 *      Author: chuanjiang.zh
 */

#include "RawMediaWriter.h"

namespace av
{

RawMediaWriter::RawMediaWriter():
		m_file(),
		m_totalBytes(),
		m_format(),
		m_startPts(-1),
		m_curPts(),
		m_listener()
{
}

RawMediaWriter::~RawMediaWriter()
{
	close();
}

bool RawMediaWriter::open(const char* filename, const MFormat& fmt)
{
	if (!filename || (strlen(filename) == 0))
	{
		return false;
	}

	m_file = fopen(filename, "wb");

	return (m_file != NULL);
}

void RawMediaWriter::close()
{
	if (m_file)
	{
		fclose(m_file);
		m_file = NULL;
	}

	m_totalBytes = 0;
	m_startPts = -1;
	m_curPts = 0;
}

bool RawMediaWriter::isOpen()
{
	return (m_file != NULL);
}

bool RawMediaWriter::getFormat(MFormat& fmt)
{
	fmt = m_format;
	return true;
}

bool RawMediaWriter::writeVideo(uint8_t* data, int size, int64_t pts, int flags)
{
	if (!data || (size <= 0))
	{
		return false;
	}

	if (m_startPts == -1)
	{
		m_startPts = pts;
	}

	m_curPts = pts;

	bool done = false;
	if (m_file != NULL)
	{
		size_t written = fwrite(data, 1, size, m_file);
		done = (written == size);
	}

	m_totalBytes += size;

	return done;
}

bool RawMediaWriter::writeAudio(uint8_t* data, int size, int64_t pts, int flags)
{
	//m_totalBytes += size;

	/// ignore
	return true;
}


int RawMediaWriter::getDuration()
{
	return (int)((m_curPts - m_startPts)/1000);
}

int64_t RawMediaWriter::getByteLength()
{
	return m_totalBytes;
}

bool RawMediaWriter::setFile(const char* filepath)
{
	if (m_file)
	{
		fclose(m_file);
		m_file = NULL;
	}

	m_file = fopen(filepath, "wb");

	return (m_file != NULL);
}

bool RawMediaWriter::setOutputAudioCodec(int codecId)
{
	return false;
}

void RawMediaWriter::setListener(MediaWriterListener* listener)
{
	m_listener = listener;
}

void RawMediaWriter::fireStatus(int status)
{
	if (m_listener)
	{
		m_listener->onWriteStatus(this, status);
	}
}

bool RawMediaWriter::setMeta(const char* key, const char* value, int size)
{
	return true;
}

} /* namespace av */
